<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" size="mini" class="role-operate" @click="showDialog = true">添加角色</el-button>
      <!-- 表格 -->
      <el-table :data="roleList">
        <el-table-column prop="name" label="角色" align="center" width="200px">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" align="center" width="200px">
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1 ? '已启用' : row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" :rows="2" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="onEditSubmit(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="openPermDialog(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="onEdit(row)">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="onDelSubmit(row.id)"
              >
                <el-button slot="reference" size="mini" type="text" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
          :page-size="params.pagesize"
          :total="total"
          :current-page="params.page"
          layout="prev, pager, next"
          @current-change="currentChange"
        />
      </el-row>
    </div>
    <!-- 添加角色的弹层 -->
    <el-dialog :visible="showDialog" width="500px" title="新增角色" @close="onCancel">
      <el-form ref="formRef" label-width="120px" :model="formModel" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formModel.name" size="mini" style="width: 300px" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch v-model="formModel.state" size="mini" style="width: 300px" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formModel.description" size="mini" type="textarea" :rows="2" style="width: 300px" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="onSubmit">确定</el-button>
              <el-button size="mini" @click="onCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限的弹层 -->
    <el-dialog :visible="showPermDialog" :title="permTitle" width="500px" @close="closePermDialog">
      <el-tree
        ref="permTreeRef"
        :data="permissionList"
        node-key="id"
        :props="{ label: 'name' }"
        default-expand-all
        show-checkbox
        check-strictly
        :default-checked-keys="permIds"
      />
      <el-row slot="footer" type="flex" justify="center" align="center">
        <el-col :span="8">
          <el-button type="primary" size="mini" @click="onPermSubmit">确认</el-button>
          <el-button size="mini" @click="closePermDialog">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { perGetPermissionListApi } from '@/api/permission'
import { roleAddRoleApi, roleAssignPermApi, roleDeleteRoleApi, roleGetRoleDetailApi, roleGetRoleListApi, roleUpdateRoleApi } from '@/api/role'
import { transListToTreeData } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      // 获取角色列表的参数
      params: {
        page: 1,
        pagesize: 4
      },
      roleList: [], // 角色列表
      total: null,
      showDialog: false, // 控制添加角色弹层的显隐
      formModel: {
        name: '',
        description: '',
        state: 1 // 未启用 0 | 启用 1  默认启用
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', triggr: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermDialog: false, // 控制分配权限弹层的显隐
      permissionList: [], // 权限点列表
      roleId: null, // 选中的当前角色 id
      permIds: [], // 角色关联的权限集合
      permTitle: ''
    }
  },
  created() {
    this.getRoleList()
    this.getPermissionList()
  },
  methods: {
    /**
     * 获取角色列表
     */
    async getRoleList() {
      const { rows, total } = await roleGetRoleListApi(this.params)
      this.roleList = rows
      this.total = total
      this.roleList.forEach((item) => {
        // 编辑标识
        this.$set(item, 'isEdit', false)
        // 缓存数据
        this.$set(item, 'editRow', { ...item })
      })
    },
    /**
     * 编辑点击事件
     * @param row 行数据
     */
    onEdit(row) {
      row.editRow.id = row.id
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
      row.isEdit = true
    },
    /**
     * 编辑时确定点击事件
     * @param row 行数据
     */
    async onEditSubmit(row) {
      if (row.editRow.name && row.editRow.description) {
        await roleUpdateRoleApi(row.editRow)
        this.$message.success('更新角色成功~')
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
      } else {
        this.$message.warning('角色名称和描述不能为空')
      }
    },
    /**
     *
     * @param id 删除时确定点击事件
     */
    async onDelSubmit(id) {
      await roleDeleteRoleApi(id)
      this.$message.success('删除角色成功~')

      if (this.roleList.length === 1) this.params.page--

      this.getRoleList()
    },
    /**
     * 页码改变时
     * @param newPage
     */
    currentChange(newPage) {
      this.params.page = newPage
      this.getRoleList()
    },
    /**
     * 弹层确定点击事件
     */
    async onSubmit() {
      await this.$refs.formRef.validate()
      await roleAddRoleApi(this.formModel)
      this.$message.success('新增角色成功~')
      this.params.page = Math.ceil((this.total + 1) / this.params.pagesize)
      this.getRoleList()
      this.onCancel()
    },
    /**
     * 关闭弹层
     */
    onCancel() {
      this.showDialog = false
      this.$refs.formRef.resetFields()
    },
    /**
     * 获取权限点列表 => 转成树形结构
     */
    async getPermissionList() {
      this.permissionList = transListToTreeData(await perGetPermissionListApi(), 0)
    },
    /**
     * 打开分配权限弹层
     * @param id 角色id
     */
    async openPermDialog(id) {
      this.roleId = id
      const { permIds, name } = await roleGetRoleDetailApi(id)
      this.permTitle = '分配权限 -- ' + name
      this.permIds = permIds
      this.showPermDialog = true
    },
    /**
     * 关闭分配权限弹层
     */
    closePermDialog() {
      this.$refs.permTreeRef.setCheckedKeys([])
      this.showPermDialog = false
    },
    /**
     * 确认给角色分配权限
     */
    async onPermSubmit() {
      await roleAssignPermApi({ id: this.roleId, permIds: this.$refs.permTreeRef.getCheckedKeys() })
      this.$message.success('分配权限成功~')
      this.closePermDialog()
    }
  }
}
</script>

<style scoped>
.role-operate {
  margin: 10px;
}
</style>
